<?php

namespace Pub\Controller;

use Common\Controller\BaseController;

class PublicController extends BaseController {

    /**
     *  用户注册
     */
    public function register() {
        $User = D("User");
        $verifyCode = $this->getParam('verifyCode', '', 'int', true, '验证码不能为空');
        $iPhone = $this->getParam('phone', '', 'mobile', true, '账号格式不正确');
        
        if (!$arrData = $User->create()) {
            $this->error($User->getError());
        }
        
        $code = S($User->phone);
        if ($code != $verifyCode) {
            $this->error("请重新发送验证码");
        }
        
        $arrData['password'] = md5($User->password);
        $arrData['type'] = 1;
        
        $userInfo = M('User')->where(array('phone' => $iPhone))->find();
        if(empty($userInfo)){
            $res = $User->add($arrData);
        }else{
            if (($userInfo['type'] & 1) == 1) {
                $this->error('该账号码已存在');
            }
            $arrData['type'] = array('exp', "type|1");  //用户所属平台（1-天网云学院 2-菁英汇  位运算）
            $res = $User->where(array('user_id'=>$userInfo['user_id']))->save($arrData);
        }
        
        S("$verifyCode", null);
        $this->success('注册成功', 1);
    }

    /**
     *  用户登录
     */
    public function login() {
        $strPhone = $this->getParam('phone', '', 'string', true, '账号码不能为空');
        $strPassword = $this->getParam('password', '', 'string', true, '密码不能为空');

        $arrAuthInfo = $this->getAuthInfo($strPhone, $strPassword);
        if (empty($arrAuthInfo)) {
            $this->error('账号或密码错误，请重新输入！');
        }
        //用户所属平台（1-天网云学院 2-菁英汇  位运算）
        if (($arrAuthInfo['type'] & 1) == 0) {
            $this->setAuthType($arrAuthInfo['user_id']);
        }

        $where['ucr.user_id'] = $arrAuthInfo['user_id'];
        $where['ucr.status'] = array('between', '0,1');
        $where['c.status'] = 1;
        $arrUserCompanyInfo = M()->table('qy_user_company_relat ucr')
                ->field("ucr.user_id,ucr.company_id, ucr.cate_id, ucr.role_id, ucr.status, d.cate_name ")
                ->join('qy_company c on c.company_id = ucr.company_id')
                ->join('LEFT JOIN qy_category_all d on ucr.cate_id = d.cate_id')
                ->where($where)
                ->find();
        
        $strUserToken = token_encrypt($arrAuthInfo['user_id']);
        cookie('token', $strUserToken);
        $arrUserInfo = array(
            'iUserId' => $arrAuthInfo['user_id'],
            'iCompanyId' => $arrUserCompanyInfo['company_id'],
            'iPostId' => $arrUserCompanyInfo['cate_id'],
            'iRoleId' => $arrUserCompanyInfo['role_id'],
            'iStatus' => $arrUserCompanyInfo['status'],
            'token' => $strUserToken
        );
        $redisResult = S($arrUserInfo['iUserId'],$arrUserInfo);

//        session('iUserId', $arrAuthInfo['user_id']);
//        session('iCompanyId', $arrUserInfo['company_id']);   //企业ID
//        session('iPostId', $arrUserInfo['cate_id']); //岗位ID
//        session('iRoleId', $arrUserInfo['role_id']); //角色ID
//        session('iStatus', $arrUserInfo['status']); //加入状态ID

        if ($redisResult) {
            //添加登录记录
            $loginRecord = R('Qy/LoginRecord/insert');
            //登录就算加入企业
            if(!empty($arrUserCompanyInfo['company_id'])){
                 $this->setJoinCompanyStatus($arrAuthInfo['user_id'], $arrUserCompanyInfo['company_id']);
            }
            if ($arrUserCompanyInfo['role_id'] == 1) {
                $arrUserCompanyInfo['cate_name'] = '运营，客服，美工，营销';
            }
            $returnData = array(
                'user_id' => $arrAuthInfo['user_id'],
                'phone' => $arrAuthInfo['phone'],
                'user_name' => $arrAuthInfo['user_name'], //角色ID
                'company_id' => $arrUserCompanyInfo['company_id'],
                'post_id' => $arrUserCompanyInfo['cate_id'], //岗位id
                'role_id' => $arrUserCompanyInfo['role_id'], //角色ID
                'status' => $arrUserCompanyInfo['status'] //状态
            );
            $this->success('登录成功！', 1, $returnData);
        } else {
            $this->error('登录失败');
        }
    }

    /**
     *  用户登出
     */
    public function logout() {
        $token = cookie('token');
        if ($token) {
            list ($iUserId, $time) = token_decrypt($token);
            if ($iUserId) {
                cookie('token', null);
                S($iUserId,null);
            }
            $this->success('登出成功！');
        } else {
            $this->success('已经登出！');
        }
//        if (isset($this->iUserId)) {
//            session_destroy();
//            $this->success('登出成功！', 1);
//        } else {
//            $this->error('已经登出！');
//        }
    }

    /**
     *  注册验证码发送
     */
    public function registerSend() {
        $this->sendCode(1);
    }

    /**
     *  修改密码证码发送
     */
    public function updatePwdSend() {
        $this->sendCode(2);
    }

    /**
     *  验证码发送
     *  @internal type: 1=>注册，2=>修改密码
     */
    public function sendCode($iType) {
        $iPhone = $this->getParam('phone', '', 'string', true, '请输入账号码');
        $SMS_TPL = C("SMS_TPL");
 
        $userRes = $this->getUser($iPhone);
        if($iType == 1){
            !empty($userRes) && $this->error('该账号码已注册');
        }elseif($iType == 2){
            empty($userRes) && $this->error('该账号码还未注册');
        }
        
        /******看不懂啊***********
        $userRes = $this->getUser($iPhone);
        if (empty($userRes)) {
            $message = $iType == 1 ? '请输入账号码' : '该账号码还未注册';
            $this->error($message);
        }
         * 
         */


        $strRand = createVerify($iPhone);
        $strMessage = str_replace('%code%', $strRand, $SMS_TPL[0]);
        $arrYzmLog = $this->getYzmLog($iPhone);
        if ($arrYzmLog['num'] >= 5) {
            $this->error('您今天发送验证码到上限，明天再来吧!');
        } elseif ($arrYzmLog['num'] > 0 && $arrYzmLog['num'] < 5) { //更新次数
            $this->updateYzmLog($arrYzmLog['id']);
        } else { //添加新数据
            $this->addYzmLog($iPhone, $strMessage);
        }
        sys_sms($iPhone, $strMessage);

        $this->success('注册码已发送', 1);
    }

    /**
     *  验证码验证
     */
    public function verify() {
        $verifyCode = $this->getParam('verifyCode', '', 'int', true, '请输入验证码！');
        $iPhone = $this->getParam('phone', '', 'string', true, '请输入账号码！');

        $code = S($iPhone);
        if (empty($code)) {
            $this->error('该验证码已过期，请重新发送');
        }
        if ($verifyCode != $code) {
            $this->error('该验证码不正确');
        }

        S($iPhone, $verifyCode, 180);
        $this->success('验证成功', 1);
    }

    /**
     *  找回密码
     *  
     */
    public function findPwd() {
        $strPhone = I('phone');
        $strPassword = I('password');
        $User = D('User');
        $verifyCode = I('verifyCode');

        $rules = array(
            array('phone', 'require', '账号码不能为空', 1),
            array('password', 'require', '密码不能为空', 1),
            array('password', '/^[\S]{6,12}$/', '密码长度要求6-12位，不限制类型', 1)
        );

        if (!$User->validate($rules)->create()) {
            $this->error($User->getError());
        }

        $user_id = M("User")->where(array('phone' => $strPhone))->getField('user_id');
        if (empty($user_id)) {
            $this->error('该账号码号码未注册');
        }
        $code = S($strPhone);
        if ($code != $verifyCode) {
            $this->error("请重新发送验证码");
        }

        $User->user_id = $user_id;
        $User->password = md5($strPassword);
        $res = $User->save();

        if ($res) {
            S("$verifyCode", null);
            $this->success('修改成功', 1);
        } else {
            $this->success('修改失败');
        }
    }

    /**
     *  获取用户详情
     */
    protected function getAuthInfo($phone, $password) {
        $result = D("User")
                ->field('user_id,user_name,phone,photo,type')
                ->where(array('phone' => $phone, 'password' => md5($password), 'type' => array('NEQ', 0)))
                ->find();

        return $result;
    }

    /**
     *  菁英汇用户更新企业权限
     */
    protected function setAuthType($user_id) {
        return M('User')->where(array('user_id' => $user_id))->setField('type', array('exp', "type|1"));
    }

    /**
     * 公用接口-岗位列表
     */
    public function postList() {
        $cateList = M('CategoryAll')->field('cate_id,cate_name')->where(array('type' => 1))->order('cate_id ASC')->select();
        $this->returnList($cateList);
    }

    /**
     * 查询用户是否存在
     */
    public function getUser($iPhone) {
        $result = M('User')
                ->where(array('phone' => $iPhone, 'type' => array('NEQ', 0)))
                ->count();
        return $result;
    }

    /**
     * 获取验证码日志
     */
    public function getYzmLog($iPhone) {
        $result = M('YzmLog')
                ->field('id,num')
                ->where("create_time >= date(now()) and create_time < DATE_ADD(date(now()),INTERVAL 1 DAY) and  phone = $iPhone")
                ->find();

        return $result;
    }

    /**
     * 更新验证码日志
     */
    public function updateYzmLog($id) {
        $result = M('YzmLog')
                ->where(array('id' => $id))
                ->setInc('num', 1);

        return $result;
    }

    /**
     * 新增验证码日志
     */
    public function addYzmLog($iPhone, $strMessage) {

        $arrData['phone'] = $iPhone;
        $arrData['code'] = $strMessage;
        $arrData['num'] = 1;
        $arrData['create_time'] = date('Y-m-d H:i:s', time());

        D('YzmLog')->add($arrData);
    }

}
